/**
 *
 */
package com.oceansoft.mobile.econsole.modules.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.modules.api.entity.CarType;
import com.oceansoft.mobile.econsole.modules.api.util.DataDirection;
import com.oceansoft.mobile.econsole.modules.api.util.SimpleDesGA;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.movecar.entity.Mes;
import com.oceansoft.mobile.econsole.modules.movecar.entity.MoveCar;
import com.oceansoft.mobile.econsole.modules.movecar.entity.MoveCarEntity;
import com.oceansoft.mobile.econsole.modules.movecar.entity.RoadBlock;
import com.oceansoft.mobile.econsole.modules.movecar.service.IMoveCarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 堵路移车
 *
 * @author jin.xu
 * @version 2015-02-28
 */
@RestController
@RequestMapping("api/movecar")
public class ApiMoveCarController extends BaseController {


    private static final Logger log = LoggerFactory.getLogger(BaseController.class);
    @Resource
	private IMoveCarService moveCarService;

    @RequestMapping(value = "index", method = GET)
	public ModelAndView index(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("weixin/movecar/move-car");
		return modelAndView;
	}
	
    @ResponseBody
    @RequestMapping(value = "movecarga", method = POST)
    public JSONObject moveCarGA(HttpServletRequest request) {
        final String imageUrl = request.getParameter("imageUrl");
        final String address = request.getParameter("address");
        final String tel = request.getParameter("tel");
        final String carNo = request.getParameter("carNo");
        final String carTypeId = request.getParameter("carTypeId");
        final String cardNo = request.getParameter("cardNo");

        try {
            String resp = HttpClientUtil.doPost("http://api.118114sz.com.cn:8090/api-v7.0.1/ws/movecar/moveCarGA", new HashMap<String, String>() {{
                put("imageUrl", SimpleDesGA.encrypt(imageUrl.trim(), DataDirection.TO_SERVER));
                put("address", SimpleDesGA.encrypt(address.trim(), DataDirection.TO_SERVER));
                put("tel", SimpleDesGA.encrypt(tel.trim(), DataDirection.TO_SERVER));
                put("carNo", SimpleDesGA.encrypt("苏E" + carNo.trim().toUpperCase(), DataDirection.TO_SERVER));
                put("carTypeId", SimpleDesGA.encrypt(carTypeId.trim(), DataDirection.TO_SERVER));
                put("cardNo", SimpleDesGA.encrypt(cardNo.trim(), DataDirection.TO_SERVER));
            }}, "UTF-8");
            return JSON.parseObject(resp);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "cartype", method = GET)
    public Result getCarType(HttpServletRequest request) {

        Map<String,String> map = (Map<String,String>)request.getSession().getServletContext().getAttribute(Constant.DICT_CAR_TYPE);
        if(map.size() > 0){
            List<CarType> list = new ArrayList<>();
            for(String key : map.keySet()){
                CarType carType = new CarType();
                carType.setCode(key);
                carType.setName(map.get(key));
                list.add(carType);
            }
            return new Result(Result.SUCC,list,"车辆类型获取成功");
        }
        return new Result(Result.FAILURE,"车辆类型获取失败");
    }

    @RequestMapping(value = "report", method = POST)
    public Result reportMoveCar(MultipartHttpServletRequest request) {

        try {
            return moveCarService.reportMoveCar(request);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "图片上传失败");
        }
    }
    /**
     * 提交堵路移车上传图片
     * @return
     */
    @RequestMapping(value = "qurl", method = POST)
    public String qurl(HttpServletRequest request) throws IOException{
        return configInfo.getServiceInterfaceAddress() + "/storage/upload";
    }

    /**
     * 提交堵路移车上传图片
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "upload", method = POST)
    public Result upload(MultipartHttpServletRequest request) throws IOException{
        String url = configInfo.getServiceInterfaceAddress() + "/storage/upload";
        Map<String, Object> test = new HashMap<String, Object>();

        test.put("file",request.getFiles("carfile"));
        JSONObject object = JSON.parseObject(HttpClientUtil.doPostString(url,test));

        System.out.println("apiPager.getList()="+HttpClientUtil.doPostString(url,test));

        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);


    }
    /**
     * 提交堵路移车
     * @param movecar
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "wx_report", method = POST)
    public Result movecarWxSubmit(MoveCar movecar,@RequestParam("Base64") String base64,HttpServletRequest request) throws Exception{
        if(!StringUtils.isEmpty(base64)){
            base64 = base64.substring(base64.lastIndexOf(",")+1, base64.length()).trim();
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
            String bizParentDir = configInfo.getBizDayDirRelPath(movecar.getReportIdCard(), configInfo.getMoveCarDir());
            String imgUrl = String.format("%s/%s", configInfo.getFileUploadRootPath() ,bizParentDir);

            BASE64Decoder decoder = new BASE64Decoder();
            FileOutputStream out = new FileOutputStream(FileUtils.createFile(new File(imgUrl), newFileName));
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            out.write(decoderBytes);
            out.flush();
            out.close();

            movecar.setImageData(decoderBytes);
            movecar.setImageUrl(configInfo.getFileDownloadUrl(bizParentDir+"/"+newFileName));
            System.out.println("getImageUrl="+movecar.getImageUrl());
            System.out.println("getImageData="+movecar.getImageData());
            request.setAttribute("imgurl", configInfo.getFileDownloadUrl(bizParentDir+"/"+newFileName));
        }
        //movecar.setCarNo("辽"+movecar.getCarNo());
        movecar.setReportAddress(movecar.getAddress());
        // 前台车牌号强制转换成大写，后台收到的仍为小写。此处转为大写
        movecar.setCarNo(movecar.getCarNo().toUpperCase());
        movecar.setReportTime(new Date());
        movecar.setId(UUID.randomUUID().toString());

        return moveCarService.reportWxMoveCar(movecar);
    }


    @ResponseBody
    @RequestMapping(value = "savedlyc", method = POST)
    public Result wscheduleDetail(HttpServletRequest request) throws IOException {
        String cartype = request.getParameter("carTypeId");
        String carnum = request.getParameter("carNo");

        String address = request.getParameter("address");
        if(Strings.isNullOrEmpty(address)){
            address="测试地址";
        }
        String picid = request.getParameter("picid");
        String pt = request.getParameter("pt");
        String aUserGuid = request.getParameter("aUserGuid");
        String aUserName = request.getParameter("aUserName");
        Result result = new Result();

        MoveCarEntity moveCarEntity=new MoveCarEntity();



        if("W".equals(pt)){//微信端
            if(Strings.isNullOrEmpty(getWxMemberSession().getGuid())){
                moveCarEntity.setUsrGuid("000000000000");
            }else {
                moveCarEntity.setUsrGuid(getWxMemberSession().getGuid());
            }
            if(Strings.isNullOrEmpty(getWxMemberSession().getRealname())){
//                moveCarEntity.setUsrName("000000000000");
                moveCarEntity.setUsrName(getWxMemberSession().getUserName());
            }else {
                moveCarEntity.setUsrName(getWxMemberSession().getRealname());
            }

            if(Strings.isNullOrEmpty(getWxMemberSession().getMobile())){
                moveCarEntity.setUsrPhone(getWxMemberSession().getTelephone());
            }else{
                moveCarEntity.setUsrPhone(getWxMemberSession().getMobile());
            }
        }else{//APP端
            moveCarEntity.setUsrGuid(aUserGuid);
            moveCarEntity.setUsrName(aUserName);
        }
        String carNumber="云"+carnum;


        moveCarEntity.setCarNumber(carNumber);
        moveCarEntity.setUsrAddr(address);
        String result1 = moveCarService.savedlyc(moveCarEntity).getMsg();
        if("堵路移车上传失败".equals(result1)){
            result.setMsg("堵路移车信息上传失败！");
            result.setSucc(false);
            return result;
        }else{
            result.setMsg("堵路移车信息上传成功！");
            result.setSucc(true);
            return result;
        }
    }
}
